<?php
/**
 * Created by PhpStorm.
 * User: N
 * Date: 2018/03/11
 * Time: 15:17
 */
namespace common\models;

use Yii;
use yii\base\Model;
use common\models\Models;
use backend\modules\content\models\Sitemodel;
use backend\modules\content\models\Modelfield;
use yii\db\ActiveRecord;
use yii\data\ActiveDataProvider;
use yii\data\Pagination;
use common\models\User;

use yii\helpers\Url;

/**
 * This is the model class for table "Branch".
 *
 * @property string $catid
 * @property string $siteid
 **/
class Branch extends ActiveRecord
{
     /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%branch}}';
    }




    /**
    * 验证规则
    */
    public function rules()
    {
        return [
                    
            [['name'],'required','message'=>'不能为空'],
           
            [['id','parentid','founding_time'],'number'],   

            [['info'],'string']         
        ];
    }

    public function beforeSave($insert){
        if($insert){
            $this->status=0;
            //插入时补充操作
        }else{
            //修改时补充操作
            // echo "update";
            // exit;
        }
        return true;
    }


    public function getUsers()
    {
        $users=[];
        $users=User::find()->where("branch_id={$this->id}")->orderBy(' id asc ')->all();
        return $users;
    }

        /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => '支部名称',
            'parentid' => '上级支部',
            'founding_time' => '创建时间',
            'info' =>'支部简介',
            'status' => '状态',
        ];
    }



   //党支部人员数量
    public function getMemberNum(){
         $count = User::find()->where(['branch_id'=>$this->id])->count();
         return $count;
    }

    //党支部人员数量
    public function getMeetingNum(){
         $count = Meeting::find()->where(['branch_id'=>$this->id])->count();
         return $count;
    }


    public function getMeetings(){
        return $this->hasMany(Meeting::className(), ['branch_id'=>'id']);
    }


        
    //获取支部书记
    public function getMaster()
    {
        return User::find()->where(['branch_id' => $this->id,'position'=>1])->one();
    }


    /**
     * 获取党支部树形结构
     * @param string $selected 当前选中的支部编号
     * @param string $str
     * @return string
     */
    public static function getMenu($selected='',$str=''){

        $branches = self::find()->asArray()->where(['status'=>0])->orderBy('listorder DESC,id DESC')->all();

        /** 实现党支部的层级下拉框  **/
        $tree= new Tree();//实例化tree
        $tree->icon = array('│ ','├─ ','└─ ');//设置一个树形数组
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';//设置空格占位符
         if(!$str) $str="<li class=\$selected ><a href='?branch_id=\$id' >\$spacer \$name</a></li>";//生成树形结构基本代码
        // $url = Url::current(['branch_id' =>$id]);
        // if(!$str) $str="<li class=\$selected ><a href='?branch_id=\$url'>\$spacer \$name</a></li>";//生成树形结构基本代码

        $Tbranches=[];
        foreach($branches as $key=>$branch)//遍历循环 对单个分类数据进行处理 并获取层级
        {
            $Tbranches[$branch['id']]['parentid']=$branch['parentid'];
            $Tbranches[$branch['id']]['name']=$branch['name'];
            $Tbranches[$branch['id']]['parentid_node']=$branch['parentid']?' class="child-of-node-'.$branch['parentid'].'"':'';//如果 $cat['parentid']不为空就赋值如果为空就赋值空
            $Tbranches[$branch['id']]['level']=self::get_level($branch['id'],$branches);//传递调用get_level方法
            $Tbranches[$branch['id']]['id']=$branch['id'];
            //$branches[$key]['selected']=in_array($branch['id'],$selectids)?'selected':'';
        }
       
        $tree->init($branches);//初始化$cate
        $branchstr = $tree->get_tree(0, $str,$selected);//生成选择框字符串
        return $branchstr;

    }

  /**
     * 获取栏目等级
     * @param $id
     * @param array $array
     * @param int $i
     * @return int
     */
    public static function get_level($id,$array=array(),$i=0)
    {
		foreach($array as $n=>$value){
			if($value['id'] == $id)
			{
				if($value['parentid']== '0') return $i;
				$i++;
				return self::get_level($value['parentid'],$array,$i);
			}
        }

    }

    /**
     * 获取支部成员
     * @param int $branch_id 支部id
     * @param string $type 返回类型，默认的json类型，其他：array数组
     * @return null
     */
    public function getMembers($branch_id=0,$type='json'){
        //若无支部编号则返回null
        if(!$branch_id){
            return null;
        }

        //验证返回类型
        if(!in_array($type,['json','array'])) $type='json';

        $members = User::find()->where(['branch_id'=>$branch_id])->select('id,username,realname,mtype,tel,address,position,status,avatar,avatar_small')->asArray()->all();

        if($type=='json') $members = json_encode($members);

        return $members;
    }


}